import React, { Component } from 'react'
import request from '../util/request'

export default class Login extends Component {
    state = {
        username:'',
        password:''
    }
    render() {
        let {username,password} = this.state;
        return (
            <div>
                <input type="text" placeholder="请输入用户名" value={username} onChange={this.change} name="username"/>
                <input type="text" placeholder="请输入密码" value={password}  onChange={this.change} name="password"/>
                <button onClick={this.login}>登录</button>
            </div>
        )
    }

    //受控表单
    change = (e) => {
        this.setState({
            [e.target.name]:e.target.value
        })

    }

    //登录
    login = () => {
        let {username,password} = this.state;
        if(username && password){
            request.post('/api/login',{username,password}).then(res => {
                console.log(res);
                if(res.data.code === 1){
                    alert('登录成功')
                    localStorage.setItem('token',res.data.token);
                    localStorage.setItem('id',res.data.id);
                    localStorage.setItem('age',res.data.age);
                    localStorage.setItem('username',res.data.username);
                    this.props.history.push('/home')
                }
            })
        }else{
            alert('参数有误')
        }
    }
}
